// editNearby.js
const db = wx.cloud.database();
const app = getApp();

Page({
  data: {
    id: '',
    city: '',
    desc: '',
    eva: '',
    img: '',
    latitude2: '',
    longitude2: '',
    name: ''
  },
  onLoad(options) {
    const { id } = options;
    this.setData({ id });

    wx.cloud.callFunction({
      name: 'nearbysearch',
      data: {
        id: id
      },
      success: res => {
        const nearbyInfo = res.result;
        this.setData({
          city: nearbyInfo.city,
          desc: nearbyInfo.desc,
          eva: nearbyInfo.eva,
          img: nearbyInfo.img,
          latitude2: nearbyInfo.latitude2,
          longitude2: nearbyInfo.longitude2,
          name: nearbyInfo.name
        });
      },
      fail: err => {
        console.error('Failed to search nearby:', err);
      }
    });
  },
  onShow() {
    const id = this.data.id;
    this.loadData(id);
  },
  submitForm(e) {
    const formData = e.detail.value;
    const id = this.data.id;
    formData.img = this.data.img;//非常关键，必须替换掉原有图片链接才能够替代更新
    db.collection('zyzl_nearbylist').doc(id).update({
      data: formData,
      success: res => {
        console.log('Update nearby successfully!', res);
        wx.showToast({
          title: 'Updated successfully!',
          icon: 'success',
          duration: 2000,
          success: () => {
            wx.navigateBack();
          }
        });
      },
      fail: err => {
        console.error('Failed to update nearby:', err);
        wx.showToast({
          title: 'Failed to update nearby!',
          icon: 'none'
        });
      }
    });
  },
  chooseImage() {
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: res => {
        const tempFilePaths = res.tempFilePaths;
        this.uploadImage(tempFilePaths[0]);
      }
    });
  },
  uploadImage(filePath) {
    const cloudPath = 'nearby/' + this.data.name + Date.now() + '.png';
    wx.cloud.uploadFile({
      cloudPath: cloudPath,
      filePath: filePath,
      success: res => {
        // 更新页面上的图片链接
        this.setData({
          img: res.fileID
        });
        wx.showToast({
          title: 'Upload successful!',
          icon: 'success'
        });
      },
      fail: err => {
        console.error('Failed to upload image:', err);
        wx.showToast({
          title: 'Failed to upload image!',
          icon: 'none'
        });
      }
    });
  }
  
});
